package com.example.springai.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/ai")
public class QianWenTest {
    /**
     * 调用模型的
     * @param args
     */


    public static void main(String[] args) {
        String requestUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
        String dashScopeApiKey = "sk-875dd6ef14244431acdc7ccb974f5bfe";
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            // 请求头
            connection.setRequestProperty("Authorization", "Bearer " + dashScopeApiKey);
            connection.setRequestProperty("Content-Type", "application/json");
            // 设置允许输出
            connection.setDoOutput(true);
            // 构造请求参数
            String requestBody = "{\n" +
                    "    \"model\": \"qwen-plus\",\n" +
                    "    \"messages\": [\n" +
                    "        {\n" +
                    "            \"role\": \"system\",\n" +
                    "            \"content\": \"You are a helpful assistant.\"\n" +
                    "        },\n" +
                    "        {\n" +
                    "            \"role\": \"user\",\n" +
                    "            \"content\": \"写一段Java的Hello World的代码\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
            // 写入请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);
            // 读取响应数据
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println("Response Body: " + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
